import React, { ForwardedRef, useImperativeHandle, useState } from 'react'
import style from './style.module.scss'
import Drawer, { IHasDrawerMethods } from '../../../widgets/Drawer'

interface ISpecSelectorProps {
    deep: number
    title: any
    values: Array<string>
    onSelect: (index: number, value: string | undefined) => void
    selected: Array<string | undefined>
    sku?: any
}

const SpecSelector = React.forwardRef<IHasDrawerMethods, ISpecSelectorProps>((props, ref) => {
    const [expend, setExpend] = useState(false)

    const close = () => {
        setExpend(false)
    }

    const open = () => {
        setExpend(true)
    }

    useImperativeHandle(ref, () => ({
        close,
        open
    }))

    const getSelectableSpec = (deep: number): string[] => {
        if (deep === 0) return Object.keys(props.sku)
        let pHead = props.sku
        for (let i = 0; i < deep; i++) {
            const nextKey = props.selected[i]
            if (nextKey) pHead = pHead[nextKey]
        }
        return Object.keys(pHead)
    }

    const handleSelectItemClick = (index: number, value: string | undefined) => {
        console.log(value)
        // 已选择，点一下取消
        if (props.selected[index] === value) {
            props.onSelect(index, undefined)
        } else {
            props.onSelect(index, value)
        }
    }

    return (
        <Drawer name="spec" expend={expend} onClose={close}>
            <div className={style.spec__selector__container}>
                <h2>选择{props.title}</h2>
                <ul className={style.spec__list}>
                    {props.values.map((value, index) => {
                        const selectable = getSelectableSpec(props.deep)
                        return (
                            <li key={index} onClick={() => handleSelectItemClick(props.deep, value)}>
                                <h4>{value}</h4>
                                {props.selected?.indexOf(value) !== -1 ? '(已选择)' : ''}
                                {selectable.indexOf(value) !== -1 ? '' : '(不可选)'}
                            </li>
                        )
                    })}
                </ul>
            </div>
        </Drawer>
    )
})

export default SpecSelector
